package com.zhang.novel.core.filter;

import com.zhang.novel.core.wrapper.XssHttpServletRequestWarpper;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XssFilter implements Filter {
    /**
     * 排除链接
     */
    private List<String> excludes = new ArrayList<>();
    /**
     * xss过滤开关
     */
    private boolean enabled = false;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化参数
        String tempExcludes = filterConfig.getInitParameter("excludes");
        String tempEnabled = filterConfig.getInitParameter("enabled");

        if (StringUtils.isNotBlank(tempExcludes)) {
            String[] urls = tempExcludes.split(",");
            for (int i = 0; null != urls && i < urls.length; i++) {
                excludes.add(urls[i]);
            }
        }

        if(StringUtils.isNotBlank(tempEnabled)){
            enabled=Boolean.valueOf(enabled);
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;

        if(handleExcludeURL(request,response)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        XssHttpServletRequestWarpper xssRequest = new XssHttpServletRequestWarpper(request);
        filterChain.doFilter(xssRequest,servletResponse);
    }

    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
        // 如果xss过滤是关闭的，就直接返回true
        if(!enabled){
            return true;
        }
        // 如果不存在排除链接，直接返回false
        if(null == excludes || excludes.isEmpty()){
            return false;
        }

        // 将当前请求与排除链接进行匹配，匹配成功就返回true，反之为false
        String url = request.getServletPath();
        for (String pattern : excludes) {
            Pattern p = Pattern.compile("^" + pattern);
            Matcher m = p.matcher(url);
            if (m.find()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {

    }
}
